import { Select } from 'antd';
import type { SelectProps, SelectValue } from 'antd/lib/select';
import classnames from 'classnames';
import { get } from 'lodash';
import React, { forwardRef, memo, useCallback, useMemo, useRef, useState } from 'react';
import styles from './index.less';
import { getGantPopupContainer } from '@/utils/utils';
const Option = Select.Option;

export interface InputSelectorProps extends Omit<SelectProps, 'mode'> {
  dataSource?: any[];
  labelProp?: string;
  valueProp?: string;
  lableType?: string;
  mode?: 'default' | 'multiple';
  inputDebounce?: boolean;
  showSearchValueInOption?: boolean;
  clearValueWhenOnBlur?: boolean;
}
const InputSelector: React.FC<InputSelectorProps> = memo(
  forwardRef(function (props: InputSelectorProps) {
    const {
      dataSource = [],
      onChange,
      className,
      onSearch,
      lableType = undefined,
      valueProp = 'value',
      labelProp = 'lable',
      mode = 'default',
      showSearchValueInOption = true,
      clearValueWhenOnBlur = false,
      ...restProps
    } = props;
    const selectRef = useRef<Select>(null);
    const blurRef = useRef<boolean>(false);
    const [searchValue, setSearchValue] = useState('');

    const children = useMemo(() => {
      let setNewValue = true;
      const options = dataSource.map((item) => {
        const value = get(item, valueProp);
        const lable = get(item, labelProp);
        if (value == searchValue) {
          setNewValue = false;
        }
        if (value && lable) {
          //兼容字符串数组的情况
          return (
            <Option key={value} value={value} data-num={lable}>
              {lableType ? lable + get(item, 'changeExt.title') : lable}
            </Option>
          );
        } else {
          return (
            <Option key={item} value={item}>
              {item}
            </Option>
          );
        }
      });

      return showSearchValueInOption && searchValue && setNewValue
        ? [
            <Option key={searchValue} value={searchValue}>
              {searchValue}
            </Option>,
            ...options,
          ]
        : options;
    }, [dataSource, labelProp, valueProp, searchValue, showSearchValueInOption, lableType]);
    const handleSearch = useCallback(
      (val, ...ags) => {
        setSearchValue(val);
        onSearch && onSearch(val);
        if (mode != 'multiple') {
          setTimeout(() => {
            if (blurRef.current) return;
            onChange && onChange(val, {} as any);
          }, 10);
        }
      },
      [onSearch, onChange],
    );
    const handleChange = useCallback(
      (value: SelectValue, option: React.ReactElement<any> | React.ReactElement<any>[]) => {
        onChange && onChange(value, option);
        setSearchValue('');
      },
      [onChange],
    );

    return (
      <Select
        getPopupContainer={getGantPopupContainer}
        className={classnames(styles.inputSelector, className)}
        notFoundContent={<div style={{ lineHeight: 2, textAlign: 'center', fontSize: 12 }}>{tr('没有查询到数据')}</div>}
        ref={selectRef}
        {...restProps}
        onChange={handleChange}
        showSearch
        showArrow
        onSearch={handleSearch}
        onBlur={(event: any) => {
          blurRef.current = true;
          restProps.onBlur?.(event);
          setSearchValue('');
          if (clearValueWhenOnBlur) {
            onChange('', {} as any);
          }
        }}
        onFocus={() => {
          blurRef.current = false;
          restProps.onFocus?.();
        }}
        mode={mode === 'multiple' ? 'multiple' : 'default'}
      >
        {children}
      </Select>
    );
  }),
);
InputSelector.defaultProps = {
  size: 'small',
  dataSource: [],
  labelProp: 'label',
  valueProp: 'value',
};
export default InputSelector;
